package com.yifei.exception.filter;

import com.yifei.model.enums.ResultCode;
import com.yifei.utils.ResponseUtil;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description: 认证异常处理
 * @Author: yiFei
 * @date: 2023/9/24 19:53
 */
@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        int status = response.getStatus();
        if (status == HttpServletResponse.SC_NOT_FOUND) {
            // 资源不存在
            ResponseUtil.writeErrMsg(response, ResultCode.RESOURCE_NOT_FOUND);
        } else {
            // 未认证或者token过期
            ResponseUtil.writeErrMsg(response, ResultCode.ACCESS_UNAUTHORIZED);
        }
    }
}
